<template>
  <div class="classfiy">
    <div class="top">
      <el-button
        class="primary"
        icon="el-icon-plus"
        size="small"
        @click="dialogFormVisible1 = true"
        >增加</el-button
      >
      <el-button
        type="danger"
        icon="el-icon-delete"
        size="small"
        @click="somedelete"
        >批量删除</el-button
      >
    </div>
    <div class="tablist">
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @row-click="Upta"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="轮播图" width="120">
          <template slot-scope="scope">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.carouselUrl"
              fit="scale-down"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="redirectUrl" label="跳转链接" width="120">
        </el-table-column>
        <el-table-column
          prop="carouselRank"
          label="排序值"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="添加时间"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="info"
              @click="dialogFormVisible2 = true"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="danger"
              slot="reference"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="totalPage"
        :hide-on-single-page="value"
        @current-change="getpage"
      >
      </el-pagination>
      <el-dialog title="添加轮播图" :visible.sync="dialogFormVisible1">
        <el-form :model="form" label-position="left" label-width="100px">
          <el-form-item
            label="图片"
            hide-required-asterisk="true"
            :rules="[
              { required: true, message: '请添加商品图片', trigger: 'blur' },
            ]"
          >
            <el-upload
              class="imgs"
              @click="addimg"
              :action="uploadImgServer"
              :show-file-list="false"
              :headers="{
                token: token,
              }"
              :on-success="handleUrlSuccess"
            >
              <i class="el-icon-plus" v-show="!addimgurl"></i>
              <el-image
                v-show="addimgurl"
                style="width: 100px; height: 100px"
                :src="addimgurl"
                fit="scale-down"
              ></el-image>
            </el-upload>
          </el-form-item>
          <el-form-item label="跳转链接">
            <el-input v-model="form.addlinks" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item
            label="排序值"
            :rules="[
              { required: true, message: '请输入排序值', trigger: 'blur' },
            ]"
          >
            <el-input v-model="form.addnum" style="width: 300px"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible1 = false" size="small"
            >取 消</el-button
          >
          <el-button class="primary" @click="determine" size="small"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <el-dialog title="修改轮播图" :visible.sync="dialogFormVisible2">
        <el-form :model="form" label-position="left" label-width="100px">
          <el-form-item
            label="图片"
            hide-required-asterisk="true"
            :rules="[
              { required: true, message: '请添加商品图片', trigger: 'blur' },
            ]"
          >
            <el-upload
              class="imgs"
              @click="addimg"
              :action="uploadImgServer"
              :show-file-list="false"
              :headers="{
                token: token,
              }"
              :on-success="handleUrlSuccess"
            >
              <i class="el-icon-plus" v-show="!Updimgurl"></i>
              <el-image
                v-show="Updimgurl"
                style="width: 100px; height: 100px"
                :src="Updimgurl"
                fit="scale-down"
              ></el-image>
            </el-upload>
          </el-form-item>
          <el-form-item label="跳转链接">
            <el-input v-model="form.Updlinks" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item
            label="排序值"
            :rules="[
              { required: true, message: '请输入排序值', trigger: 'blur' },
            ]"
          >
            <el-input v-model="form.Updnum" style="width: 300px"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible2 = false" size="small"
            >取 消</el-button
          >
          <el-button class="primary" @click="updataS" size="small"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
let imgupdata = null;
export default {
  data() {
    const uploadImgServer =
      "http://backend-api-02.newbee.ltd/manage-api/v1/upload/file";
    return {
      uploadImgServer,
      value: true,
      token: localStorage.getItem("token") || "",
      pageNumber: 1,
      totalPage: 0,
      visible: false,
      addimgurl: "",
      Updimgurl: "",
      tableData: [],
      multipleSelection: [],
      dialogTableVisible: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      form: {
        id: "",
        addlinks: "",
        addnum: "",
        Updlinks: "",
        Updnum: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
    };
  },
  created() {
    this.getData();
  },

  methods: {
    getData() {
      this.$request
        .get("/carousels", {
          params: {
            pageNumber: this.pageNumber,
            pageSize: 10,
          },
          headers: {
            "X-Requested-With": "XMLHttpRequest",
            token: localStorage.getItem("token") || "",
          },
        })
        .then((data) => {
          this.tableData = data.data.data.list;
          // console.log("daad", this.tableData);
          this.totalPage = data.data.data.totalPage * 10;
        });
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 删除(未实现)
    handleDelete(index, row) {
      // index为索引，row为此点击的商品数据
      // console.log(row.carouselId);
      this.$request
        .delete("/carousels", {
          data: {
            ids: [row.carouselId],
          },
          headers: {
            "X-Requested-With": "XMLHttpRequest",
            token: localStorage.getItem("token") || "",
          },
        })
        .then(() => {
          // console.log("删除成功");
          this.getData();
        });
      // console.log(index, row);
    },
    handleUrlSuccess(val) {
      console.log(val);
      this.addimgurl = val.data || "";
      this.Updimgurl = val.data || "";
    },
    getpage(count) {
      this.pageNumber = count;
      this.getData();
    },
    // 添加商品按钮
    determine() {
      this.$request
        .post(
          "/carousels",
          {
            carouselUrl: this.addimgurl,
            // carouselUrl:
            //   "http://backend-api-02.newbee.ltd/upload/20211106_16470961.jpg",
            redirectUrl: this.form.addlinks,
            carouselRank: this.form.addnum,
          },
          {
            headers: {
              "X-Requested-With": "XMLHttpRequest",
              token: localStorage.getItem("token") || "",
              "Content-Type": "application/json",
            },
          }
        )
        .then((data) => {
          console.log("增加轮播图", data);
          this.getData();
          this.dialogFormVisible1 = false;
        });
      // if (this.dialogFormVisible2 == false) {
      //   this.form.links = "";
      //   this.form.num = "";
      //   this.imgurl = "";
      // }

      // 可以拿到所填写的以下数据
      // this.form.links：跳转连接
      // this.form.num排序值
      // this.imgurl上传照片路径
      // console.log(1);
      // console.log(this.form.links, this.form.num, this.imgurl);

      // 当弹出框消失时，清除弹出框内的内容
      this.form.addlinks = "";
      this.form.addnum = "";
      this.addimgurl = "";
    },

    // 点击修改按钮获取当前点击商品数据
    Upta(val) {
      // console.log(val);
      // 弹出框显示就直接把原有数据显示出来
      // 获取当前点击行
      // console.log(val);
      if (this.dialogFormVisible2 == true) {
        this.id = val.carouselId;
        this.Updimgurl = val.carouselUrl;
        this.form.Updlinks = val.redirectUrl;
        this.form.Updnum = val.carouselRank;
      }
    },
    // 点击确认修改
    updataS() {
      // console.log("this.Updimgurl", this.Updimgurl);
      this.$request
        .put(
          "/carousels",
          {
            carouselId: this.id,
            carouselUrl: this.Updimgurl,
            redirectUrl: this.form.Updlinks,
            carouselRank: this.form.Updnum,
          },
          {
            headers: {
              "X-Requested-With": "XMLHttpRequest",
              token: localStorage.getItem("token") || "",
              "Content-Type": "application/json",
            },
          }
        )
        .then((data) => {
          // console.log("ta", this.tableData);
          // console.log(this.id);
          // console.log("this.Updimgurl", this.Updimgurl);
          // console.log('carouselUrl',carouselUrl);
          // console.log("dd", data);
          this.getData();
        });

      // console.log(this.form.Updlinks);
      // 点击后修改数据库的数据
      this.dialogFormVisible2 = false;
    },
    // 批量删除(未实现)
    somedelete() {
      // console.log(this.multipleSelection);
      if (this.multipleSelection.length == 0) {
        console.log("请选择项");
        return;
      }
      this.$request
        .delete("/carousels", {
          data: {
            ids: this.multipleSelection.map((i) => i.carouselId),
          },
          headers: {
            "X-Requested-With": "XMLHttpRequest",
            token: localStorage.getItem("token") || "",
          },
        })
        .then(() => {
          // console.log("删除成功");
          this.getData();
        });
    },
    // 添加图片
    addimg() {
      if (!imgupdata) {
        // 生成文件上传的控件
        imgupdata = document.createElement("input");
        imgupdata.setAttribute("type", "file");
        imgupdata.style.display = "none";
        //  监听事件
        if (window.addEventListener) {
          // ie9及上的浏览器识别
          imgupdata.addEventListener("change", this.uploadfile, false);
        } else {
          // ie8及以下浏览器识别
          imgupdata.attachEvent("onchange", this.uploadfile);
        }
        document.body.appendChild(imgupdata);
      }
      imgupdata.click();
    },
    uploadfile(el) {
      // console.log("el", el);
      if (el && el.target && el.target.files && el.target.files.length > 0) {
        // console.log(el);
        const files = el.target.files[0];
        // 判断是否为图片格式
        if (files.type.indexOf("image") === -1) {
          console.log("请选择图片文件");
        } else {
          const that = this;
          const reader = new FileReader(); //创建读取文件对象
          // 发起异步请求，读取文件
          reader.readAsDataURL(el.target.files[0]);
          // 文件读取成功
          reader.onload = function () {
            // console.log("this.result", this.result);
            that.Updimgurl = this.result;
            that.addimgurl = this.result;
            // console.log("ret", that.Updimgurl, "/", this.Updimgurl);
            // console.log(this.result);
            // 数据传到后台
            // const formDate=new FormData();
            // 传到后台的数据
            // formDate.append('file',files);
            // console.log(formDate);
          };
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.classfiy {
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  .top {
    padding: 18px 20px;
    border: 1px solid #ebeef5;
    .primary {
      color: #fff;
      background-color: #1baeae;
      border-color: #1baeae;
    }
  }
  .tablist {
    padding: 20px;
    .el-dialog {
      width: 410px !important;
      .el-form-item {
        display: flex;
        // justify-content: space-between;
        align-items: center;
        .imgs {
          width: 100px;
          height: 100px;
          border: 1px solid #ebeef5;
          text-align: center;
          // padding-top: 20px;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          justify-content: center;
          .el-icon-plus {
            font-size: 50px;
            color: #ebeef5;
          }
        }
      }
      .primary {
        color: #fff;
        background-color: #1baeae;
        border-color: #1baeae;
      }
    }
  }
}
</style>
